package server;

import client.MapleCharacter;
import client.MapleClient;
import client.inventory.*;
import constants.GameConstants;
import database.BeePool;
import tools.FileoutputUtil;
import tools.Pair;
import tools.packet.MTSCSPacket;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CashShop implements Serializable {
    private static long serialVersionUID = 231541893513373579L;
    private int accountId;
    private int characterId;
    private ItemLoader factory;
    private List<IItem> inventory;
    private List<Integer> uniqueids;

    public CashShop(int accountId, int characterId, int jobType) throws SQLException {
        this.inventory = (List<IItem>) new ArrayList();
        this.uniqueids = (List<Integer>) new ArrayList();
        this.accountId = accountId;
        this.characterId = characterId;
        this.factory = ItemLoader.CASHSHOP_EXPLORER;
        for (Pair<IItem, MapleInventoryType> item : this.factory.loadItems(false, Integer.valueOf(accountId)).values()) {
            this.inventory.add(item.getLeft());
        }
    }

    public int getItemsSize() {
        return this.inventory.size();
    }

    public List<IItem> getInventory() {
        return this.inventory;
    }

    public IItem findByCashId(int cashId) {
        for (IItem item : this.inventory) {
            if (item.getUniqueId() == cashId) {
                return item;
            }
        }
        return null;
    }

    public void checkExpire(MapleClient c) {
        List<IItem> toberemove = (List<IItem>) new ArrayList();
        for (IItem item : this.inventory) {
            if (item != null && !GameConstants.isPet(item.getItemId()) && item.getExpiration() > 0L && item.getExpiration() < System.currentTimeMillis()) {
                toberemove.add(item);
            }
        }
        if (toberemove.size() > 0) {
            for (IItem item : toberemove) {
                this.removeFromInventory(item);
                c.sendPacket(MTSCSPacket.cashItemExpired(item.getUniqueId()));
            }
            toberemove.clear();
        }
    }

    public IItem toItem(CashItemInfo cItem, MapleCharacter chr) {
        return this.toItem(cItem, MapleInventoryManipulator.getUniqueId(cItem.getId(), null), "", chr);
    }

    public IItem toItem(CashItemInfo cItem) {
        return this.toItem(cItem, MapleInventoryManipulator.getUniqueId(cItem.getId(), null), "");
    }

    public IItem toItem(CashItemInfo cItem, String gift) {
        return this.toItem(cItem, MapleInventoryManipulator.getUniqueId(cItem.getId(), null), gift);
    }

    public IItem toItem(CashItemInfo cItem, int uniqueid) {
        return this.toItem(cItem, uniqueid, "");
    }

    public IItem toItem(CashItemInfo cItem, int uniqueid, String gift) {
        return this.toItem(cItem, null, uniqueid, gift);
    }

    public IItem toItem(CashItemInfo cItem, int uniqueid, String gift, MapleCharacter chr) {
        return this.toItem(cItem, chr, uniqueid, gift);
    }

    public IItem toItem(CashItemInfo cItem, MapleCharacter chr, int uniqueid, String gift) {
        if (uniqueid <= 0) {
            uniqueid = MapleInventoryIdentifier.getInstance();
        }
        long period = (long) cItem.getPeriod();
        if (GameConstants.isPet(cItem.getId())) {
            period = 90L;
        }
        IItem ret = null;
        if (GameConstants.getInventoryType(cItem.getId()) == MapleInventoryType.EQUIP) {
            Equip eq = (Equip) MapleItemInformationProvider.getInstance().getEquipById(cItem.getId());
            eq.setUniqueId(uniqueid);
            if (GameConstants.isPet(cItem.getId()) || period > 0L) {
                eq.setExpiration(System.currentTimeMillis() + period * 24L * 60L * 60L * 1000L);
            }
            eq.setGiftFrom(gift);
            if (GameConstants.isEffectRing(cItem.getId()) && uniqueid > 0) {
                MapleRing ring = MapleRing.loadFromDb(uniqueid);
                if (ring != null) {
                    eq.setRing(ring);
                }
            }
            ret = eq.copy();
        } else {
            Item item = new Item(cItem.getId(), (short) 0, (short) cItem.getCount(), (byte) 0, uniqueid);
            if (period > 0L) {
                item.setExpiration(System.currentTimeMillis() + period * 24L * 60L * 60L * 1000L);
            }
            if (cItem.getId() == 5211047 || cItem.getId() == 5360014) {
                item.setExpiration(System.currentTimeMillis() + 10800000L);
            }
            item.setGiftFrom(gift);
            if (GameConstants.isPet(cItem.getId())) {
                MaplePet pet = MaplePet.createPet(cItem.getId(), uniqueid);
                if (pet != null) {
                    item.setPet(pet);
                }
            }
            ret = item.copy();
        }
        return ret;
    }

    public void addToInventory(IItem item) {
        this.inventory.add(item);
    }

    public void removeFromInventory(IItem item) {
        this.inventory.remove(item);
    }

    public void gift(int recipient, String from, String message, int sn) {
        this.gift(recipient, from, message, sn, 0);
    }

    public void gift(int recipient, String from, String message, int sn, int uniqueid) {
        try (Connection con = BeePool.getConnection()) {
            PreparedStatement ps = con.prepareStatement("INSERT INTO `gifts` VALUES (DEFAULT, ?, ?, ?, ?, ?)");
            ps.setInt(1, recipient);
            ps.setString(2, from);
            ps.setString(3, message);
            ps.setInt(4, sn);
            ps.setInt(5, uniqueid);
            ps.executeUpdate();
            ps.close();
            
        } catch (SQLException sqle) {
            sqle.printStackTrace();
            FileoutputUtil.outError("logs/资料库异常.txt", (Throwable) sqle);
        }
    }

    public List<Pair<IItem, String>> loadGifts() {
        List<Pair<IItem, String>> gifts = (List<Pair<IItem, String>>) new ArrayList();
        try (Connection con = BeePool.getConnection()) {
            PreparedStatement ps = con.prepareStatement("SELECT * FROM `gifts` WHERE `recipient` = ?");
            ps.setInt(1, this.characterId);
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                CashItemInfo cItem = CashItemFactory.getInstance().getItem(rs.getInt("sn"));
                if (cItem == null) {
                    continue;
                }
                IItem item = this.toItem(cItem, rs.getInt("uniqueid"), rs.getString("from"));
                gifts.add(new Pair(item, rs.getString("message")));
                this.uniqueids.add(Integer.valueOf(item.getUniqueId()));
                List<CashItemInfo> packages = CashItemFactory.getInstance().getPackageItems(cItem.getId());
                if (packages != null && packages.size() > 0) {
                    for (CashItemInfo packageItem : packages) {
                        this.addToInventory(this.toItem(packageItem, rs.getString("from")));
                    }
                } else {
                    this.addToInventory(item);
                }
            }
            rs.close();
            ps.close();
            ps = con.prepareStatement("DELETE FROM `gifts` WHERE `recipient` = ?");
            ps.setInt(1, this.characterId);
            ps.executeUpdate();
            ps.close();
            
            this.save(null);
        } catch (SQLException sqle) {
            FileoutputUtil.outError("logs/资料库异常.txt", (Throwable) sqle);
            sqle.printStackTrace();
        }
        return gifts;
    }

    public boolean canSendNote(int uniqueid) {
        return this.uniqueids.contains(Integer.valueOf(uniqueid));
    }

    public void sendedNote(int uniqueid) {
        for (int i = 0; i < this.uniqueids.size(); ++i) {
            if (((Integer) this.uniqueids.get(i)).intValue() == uniqueid) {
                this.uniqueids.remove(i);
            }
        }
    }

    public void save(Connection con) throws SQLException {
        List<Pair<IItem, MapleInventoryType>> itemsWithType = (List<Pair<IItem, MapleInventoryType>>) new ArrayList();
        for (IItem item : this.inventory) {
            itemsWithType.add(new Pair(item, GameConstants.getInventoryType(item.getItemId())));
        }
        if (con != null) {
            this.factory.saveItems(itemsWithType, con, Integer.valueOf(this.accountId));
        } else {
            this.factory.saveItems(itemsWithType, Integer.valueOf(this.accountId));
        }
    }
}
